package com.pai4j.pay.filter;

import com.pai4j.common.helper.SessionHelper;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 程序员七七
 * @Date: 16.11.21 11:26 下午
 */
@Slf4j
@Order(-5)
@WebFilter(filterName = "paymentPreFilter", urlPatterns = {"/*"})
@Component
public class PaymentPreFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String logId = request.getHeader("log-id");
        String accessToken = request.getHeader("access-token");
        if (StringUtils.isNotBlank(logId)) {
            SessionHelper.setTraceId(logId);
        }
        if (StringUtils.isNotBlank(accessToken)) {
            SessionHelper.setToken(accessToken);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            SessionHelper.clear();
        }
    }

    @Override
    public void destroy() {

    }
}
